﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsSample
{
    public partial class AnswerForm : Form
    {
        AsyncFunc<string, string> getAnswer;

        public AnswerForm()
        {
            InitializeComponent();
            getAnswer = new AsyncFunc<string, string>(GetAnswer);
            getAnswer.Completed += new AsyncFuncCompletedEventHandler<string>(getAnswer_Completed);
            getAnswer.ProgressChanged += (s, a) => progressBar1.Value = a.ProgressPercentage;
        }

        void getAnswer_Completed(object sender, AsyncFuncCompletedEventArgs<string> e)
        {
            if (e.Error != null)
            {
                // Report exception
            }
            else if (e.Cancelled)
            {
                // Ignore
                MessageBox.Show("Operation cancelled");
            }
            else
            {
                textBox1.Text = e.Result;
            }
            progressBar1.Value = 0;
        }

        private void findAnswer_Click(object sender, EventArgs e)
        {
               getAnswer.TryInvokeAsync("What is the Answer to the Ultimate Question of Life, the Universe and Everything");
        }

        // Extremely complex stuff
        private string GetAnswer(string question, Func<bool> isCancelled, Action<int> reportProgress)
        {
            for (int i = 0; i < 100; i++)
            {
                if (isCancelled()) return null;
                reportProgress(i);
                System.Threading.Thread.Sleep(50);
            }
            return "42";
        }

        private void cancel_Click(object sender, EventArgs e)
        {
            getAnswer.Cancel();
        }

    }
}
